import {createRouter, createWebHistory} from "vue-router"
import {getJwt} from "@/api/jwt.js"

const routes = [{
    name: "login",
    path: "/login",
    component: () => import("@/components/view/Login.vue")
}, {
    name: "register",
    path: "/register",
    component: () => import("@/components/view/Register.vue")
},
    {
        name: "main",
        path: "/main",
        component: () => import("@/components/view/Main.vue"),
        redirect: '/main/home',
        children: [{
            name: "home",
            path: "/main/home",
            component: () => import("@/components/view/Home.vue")
        }, {
            name: "reserveCourse",
            path: "/main/reserveCourse",
            component: () => import("@/components/view/ReserveCourse.vue")

        },
            {
                name: "myCourse",
                path: "/main/myCourse",
                component: () => import("@/components/view/MyCourse.vue")
            }, {
                name: "mine",
                path: "/main/mine",
                component: () => import("@/components/view/Mine.vue")
            }]
    },
    {
        path: '/',
        redirect: '/login'
    }];

const router = createRouter({
    history: createWebHistory(),
    routes
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
    // 获取JWT token
    const token = getJwt()

    // 检查目标路由是否需要认证
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

    // 如果访问需要认证的页面但没有token，重定向到登录页
    if (requiresAuth && !token) {
        next('/login')
    }
    // 如果已经登录且试图访问登录页，则重定向到主页
    else if (to.path === '/login' && token) {
        next('/main')
    }
    // 其他情况允许访问
    else {
        next()
    }
})

export default router;